package com.echo.im.engin.netty.packet;

import com.echo.im.engin.packet.Packet;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class PacketManager {
    private static Map<Byte, Class<? extends Packet>> commandPacketMap = new HashMap<>();

    static {
        initializePacketMap();
    }

    private static void initializePacketMap() {
        Reflections reflections = new Reflections("com.echo.im.engin.packet", new SubTypesScanner(false));
        Set<Class<? extends Packet>> classes = reflections.getSubTypesOf(Packet.class);
        
        for (Class<? extends Packet> packetClass : classes) {
            try {
                Packet packetInstance = packetClass.getDeclaredConstructor().newInstance();
                commandPacketMap.put(packetInstance.getCommand(), packetClass);
            } catch (Exception e) {
                System.err.println("Error registering packet class: " + packetClass.getName());
                e.printStackTrace();
            }
        }
    }

    public static Class<? extends Packet> getPacketClassByCommand(Byte command) {
        return commandPacketMap.get(command);
    }
}
